<?php

namespace Phone\Model;

use Think\Model;

/**
 * 商品
 */
class GoodsModel extends Model {
    
     /**
     * 获得筛选品牌
     * @param int $cat_id 类别ID
     */
    public function get_search_brand($conditions) {
        $sql = "select distinct b.brand_id,b.brand_name,b.logo from ".C('DB_PREFIX')."goods_brand b,".C('DB_PREFIX')."goods g where g.status=1 and g.brand_id=b.brand_id ";
        foreach($conditions as $k => $v) {
            if ($k == 'cid' &&!empty($v)) {//类别
                $str_cat_id = '%,'.$v.',%';
                $sql .= "and g.cat_path_ids like '$str_cat_id' ";
            } elseif ($k == 'keywords' && !empty($v)) {//价格
                $sql .= "and (g.goods_name like '%$v%' or g.cuxiao_msg like '%$v%' or g.goods_sn like '%$v%' )";
             } elseif ($k == 'price' && !empty($v)) {//价格
                $arr_price = explode('-',$v);
                $sql .= "and g.price between '".$arr_price[0]."' and '".$arr_price[1]."' ";
            } elseif (strpos($k,'attr_') === 0) { //自定义参数
                $sql .= "and g.search_str like '%,". $k ."_" . $v . ",%' ";
            }
        }
        $sql .= " order by b.order_id asc";
        return $this->query($sql); 
    }
    
    /**
     * 获得搜索自定义参数搜索
     * @param array $conditions 搜索条件数组
     */
    public function get_search_arr($conditions) {
        $t_g = C('DB_PREFIX').'goods';//产品表
        $t_attr =  C('DB_PREFIX').'goods_mod_attr';//产品属性表
        $t_attr_v =  C('DB_PREFIX').'goods_attr_value';//产品属性值表
        $sql_from = "from ".$t_g." g,".$t_attr_v." tv,".$t_attr." t";
        $sql_where = " where g.goods_id=tv.goods_id and g.status=1 and t.attr_id=tv.attr_id and t.is_search in(2,3) ";
        
        foreach($conditions as $k => $v) {
            if ($k == 'cid' && !empty($v)) {//类别
                $str_cat_id = '%,'.$v.',%';
                $sql_where .= "and g.cat_path_ids like '$str_cat_id' ";
            } elseif ($k == 'bid' && !empty($v)) {
                $sql_where.="and g.brand_id = '".$v."' ";
            } elseif ($k == 'price' && !empty($v)) {//价格
                $arr_price = explode('-',$v);
                $sql_where .= "and g.price between '".$arr_price[0]."' and '".$arr_price[1]."' ";
            }
        }
       
        $sql = "select distinct tv.attr_id ".$sql_from.$sql_where;
        $attr_list = $this->query($sql);//获得所选类别与品牌商品的搜索属性
        $M_attr = D('goods_mod_attr');
        $M_mod_sel = D('goods_mod_sel');
        foreach($attr_list as $k => $v) {
            if(!isset($conditions['attr_'.$v['attr_id']])) {//未选择
                $attr_list[$k]['attr_name'] = $M_attr->getFieldByAttrId($v['attr_id'],'attr_name');
                $sql_where2 = $sql_where . " and t.attr_id=".$v['attr_id'];
                $attr_type = $M_attr->getFieldByAttrId($v['attr_id'],'attr_type');
                foreach($conditions as $k3 => $v3) {
                    if (strpos($k3,'attr_') === 0 && $k3 !== 'attr_'.$v['attr_id']) { //自定义参数
                       $sql_where2 .= " and g.search_str like '%,". $k3 ."_" . $v3 . ",%' ";
                    } 
                }
                $attr_value_list = $this->query('select distinct tv.attr_value '.$sql_from.$sql_where2);
                if($attr_type == 4) {//如果属性是多选框
                   
                    $attr_value_new_list = array();
                    foreach($attr_value_list as $k21 => $v21) {
                        $arr_attr_value = explode(',',$v21['attr_value']);
                        $attr_value_new_list = array_merge($attr_value_new_list,$arr_attr_value);
                    }
                    $attr_value_list =  array_unique(array_filter($attr_value_new_list));//过滤空数组和重复
                    foreach($attr_value_list as $k2 => $v2) {
                        $attr_value_list2 = array();
                        $attr_value_list2['attr_value'] = $v2;
                        $attr_value_list2['attr_value_name'] = $M_mod_sel->getFieldByAttrSelId($v2,'attr_sel_name');
                        $attr_value_list2['url'] = $this->search_url($conditions, 'attr_'.$v['attr_id'], $v2);
                        $attr_value_list[$k2] = $attr_value_list2;
                     }
                } else {
                    foreach($attr_value_list as $k2 => $v2) {
                        $attr_value_list[$k2]['attr_value_name'] = $M_mod_sel->getFieldByAttrSelId($v2['attr_value'],'attr_sel_name');
                        $attr_value_list[$k2]['url'] = $this->search_url($conditions, 'attr_'.$v['attr_id'], $v2['attr_value']);
                    }
                }
                $attr_list[$k]['sub'] = $attr_value_list;
                
            } else {
               unset($attr_list[$k]);
            }
        }
        return $attr_list;
    }
    
    /**
     * 获得价格区间
     * @param array $conditions 搜索条件数组
     * @param int $nums 价格显示个数
     * @return 搜索数组
     */
    public function get_search_price($conditions,$nums) {
        $map = array();
        $map['status'] = 1;//只显示上架商品
        foreach($conditions as $k => $v) {
            if ($k == 'title') { //关键词
                $map['goods_name|goods_sn'] = array('like', '%' . $v . '%');
            } elseif ($k == 'cid' && !empty($v)) {//类别
                $map['cat_path_ids'] = array('like', '%,' . $v . ',%');
            } elseif ($k == 'bid'  && !empty($v)) { //品牌
                $map['brand_id'] = $v;
            } elseif (strpos($k,'attr_') === 0) { //自定义参数
                if(!empty($map['_string'])) $map['_string'].= ' and ';
                $map['_string'] .= " search_str like '%,". $k ."_" . $v . ",%'";
            }
        }
        $max_price = $this->where($map)->max('price');//最低价
        $min_price = $this->where($map)->min('price');//最高价
        if($max_price == $min_price) return array();
        $avg_price = round(($max_price - $min_price)/$nums);//平均价
        $arr = array();
        $max[0] = floor($min_price);
        for($i = 1; $i<=$nums; $i++) {
            $min[$i] = $max[$i-1] + 1;
            $max[$i] = $min[$i] + $avg_price;
            if($i == 1)$min[$i] = floor($min_price);//第一个
            if($i == $nums)$max[$i] = ceil($max_price);//最后一个
            $text[$i] = $min[$i].'-'.$max[$i];
            $arr[$i] = array('min'=>$min[$i],'max'=>$max[$i],'text'=>$text[$i],'url'=>$this->search_url($conditions, 'price', $text[$i]));
        }
        return $arr;
    }
    
    /**
     * 排序参数
     * @param array $conditions 搜索条件数组
     * @return array 排序数组
     */
    public function get_search_order($conditions) {
        $arr = array();
        $arr[0] = array('text'=>'按默认排序','url'=>$this->search_url($conditions,'o',''),'name'=>'');
        $arr[1] = array('text'=>'按销量降序','url'=>$this->search_url($conditions,'o','sale_desc'),'name'=>'sale_desc');
        $arr[2] = array('text'=>'按价格降序','url'=>$this->search_url($conditions,'o','price_desc'),'name'=>'price_desc');
        $arr[3] = array('text'=>'按价格升序','url'=>$this->search_url($conditions,'o','price_asc'),'name'=>'price_asc');
        $arr[4] = array('text'=>'按收藏降序','url'=>$this->search_url($conditions,'o','fav_desc'),'name'=>'fav_desc');
        $arr[5] = array('text'=>'按浏览降序','url'=>$this->search_url($conditions,'o','hits_desc'),'name'=>'hits_desc');
        $arr[6] = array('text'=>'按上架时间','url'=>$this->search_url($conditions,'o','time_desc'),'name'=>'time_desc');
        $arr[7] = array('text'=>'按上架时间','url'=>$this->search_url($conditions,'o','time_asc'),'name'=>'time_asc');
        return $arr;
    }

    /**
     * 商品搜索
     * @param array $conditions 条件数组
     * @param int $page 分页数
     */
    public function search($conditions, $page = 20) {
        $map = array();
        $field = 'goods_id,goods_name,goods_sn,cuxiao_msg,price,price_market,count_sale,picture';
        $map['status'] = 1;//只显示上架商品
        foreach($conditions as $k => $v) {
            if ($k == 'keywords') { //关键词
                $map['goods_name|cuxiao_msg|goods_sn'] = array('like', '%' . $v . '%');
            } elseif ($k == 'cid' && !empty($v)) {//类别
                $map['cat_path_ids'] = array('like', '%,' . $v . ',%');
            } elseif ($k == 'bid'  && !empty($v)) { //品牌
                $map['brand_id'] = $v;
            } elseif ($k == 'price' && !empty($v)) {//价格
                $arr_price = explode('-',$conditions['price']);
                $map['price'] = array('between',$arr_price[0].','.$arr_price[1]);
            } elseif (strpos($k,'attr_') === 0) { //自定义参数
                if(!empty($map['_string'])) $map['_string'].= ' and ';
                $map['_string'] .= " search_str like '%,". $k ."_" . $v . ",%'";
            }
        }
        //排序
        $order = 'order_id asc,goods_id desc';
        if($conditions['o'] == 'sale_desc') {
            $order = 'count_sale desc';
        } elseif ($conditions['o'] == 'price_desc') {
            $order = 'price desc ';
        } elseif ($conditions['o'] == 'price_asc') {
            $order = 'price asc ';
        } elseif ($conditions['o'] == 'fav_desc') {
            $order = 'count_fav desc ';
        } elseif ($conditions['o'] == 'hits_desc') {
            $order = 'count_hits desc ';
        }elseif ($conditions['o'] == 'time_asc') {
            $order = 'time_create asc ';
        }elseif ($conditions['o'] == 'time_desc') {
            $order = 'time_create desc ';
        }
		
		
        
        $count = $this->where($map)->count(); // 查询满足要求的总记录数

        $Page = new \Think\Page($count, $page); // 实例化分页类 传入总记录数和每页显示的记录数
        //分页跳转的时候保证查询条件
        foreach ($conditions as $key => $val) {
            $Page->parameter[$key] = urlencode($val);
        }
        $show = $Page->show(); // 分页显示输出
        //获取分页数据
        $list = $this->field($field)->where($map)->order($order)->limit($Page->firstRow . ',' . $Page->listRows)->select();
        
        $total_page = $Page->totalPages; //总页数
        if(empty($total_page)) {
            $total_page = 0;
        }
        
        return array(
            'list' => $list,
            'page' => $show,
            'count' => $count,
            'page_count' => $total_page
        );
    }
	
	
	  /**
     * 商品搜索
     * @param array $conditions 条件数组
     * @param int $page 分页数
     */
    public function search_condition($conditions) {
        $map = array();
        $field = 'goods_id,goods_name,goods_sn,cuxiao_msg,price,price_market,count_sale,picture';
        $map['status'] = 1;//只显示上架商品
        foreach($conditions as $k => $v) {
            if ($k == 'keywords') { //关键词
                $map['goods_name|cuxiao_msg|goods_sn'] = array('like', '%' . $v . '%');
            } elseif ($k == 'cid' && !empty($v)) {//类别
                $map['cat_path_ids'] = array('like', '%,' . $v . ',%');
            } elseif ($k == 'bid'  && !empty($v)) { //品牌
                $map['brand_id'] = $v;
            } elseif ($k == 'price' && !empty($v)) {//价格
                $arr_price = explode('-',$conditions['price']);
                $map['price'] = array('between',$arr_price[0].','.$arr_price[1]);
            } elseif (strpos($k,'attr_') === 0) { //自定义参数
                if(!empty($map['_string'])) $map['_string'].= ' and ';
                $map['_string'] .= " search_str like '%,". $k ."_" . $v . ",%'";
            }
        }
        
		  return $map;

    }
    
    
    /*
     * 计算路径URL
     */
    public function search_url($arr,$k,$v) {
        $exist = false;
        foreach($arr as $k2 => $v2) {
            if($k2 == $k) {
		
                $arr[$k2] = $v;
                $exist = true;
            }
            //如果值为空删掉
            if(empty($arr[$k2])) {
                unset($arr[$k2]);
            }
			if($k2=='keywords'){
			 $arr[$k2] = urlencode($v2);
			}
        }
        if($exist == false)$arr[$k] = $v;
        return U('GList/index',$arr);
    }
    
    /*
     * 获得商品单件
     */
    public function get_item($goods_id) {
        $MGoodsItem = M('goods_item');
        $list =  $MGoodsItem->where('goods_id='.$goods_id)->select();
        return $list;
    }
    
    /*
     * 获得默认商品单件
     */
    public function get_item_first($goods_id,$item_id = 0) {
        $MGoodsItem = M('goods_item');
        $where['goods_id'] = $goods_id;
        if($item_id > 0) {
            $where['item_id'] = $item_id;
        }
        $list =  $MGoodsItem->field('spec_array,item_id')->where($where)->find();
        return $list;
    }
    
    /*
     * 获取商品默认的item_id
     */
    public function get_default_item_id($goods_id) {
        $MGoodsItem = M('goods_item');
        $item_id =  $MGoodsItem->where('goods_id='.$goods_id)->limit(1)->getField('item_id');
        //echo $MGoodsItem->_sql();
        return $item_id;
    }
    
     /*
     * 获得商品单件
     */
    public function get_item_spec($goods_id,$spec) {
        $MGoodsItem = M('goods_item');
        $row =  $MGoodsItem->where(array('goods_id'=>$goods_id,'spec_array'=>$spec))->find();
        return $row;
    }
    
   /*
     * 是否参数存在单件
     */
    public function exist_item($goods_id,$par) {
        $MGoodsItem = M('goods_item');
        $count =  $MGoodsItem->where(array('goods_id'=>$goods_id,'spec_array'=>array('like','%'.$par.'%')))->count();
        return $count;
    }
    
    /*
     * 获得商品购物车行数据
     */
    public function get_item_cart($item_id,$goods_id) {
        $MGoodsItem = M('goods_item');
        $goods = $this->field('goods_name,cuxiao_msg,picture,brand_id,status,unit,point,qi_sale')->where(array('goods_id'=>$goods_id,'status'=>1))->find();
        $item = $MGoodsItem->where(array('item_id'=>$item_id))->find();
        if(empty($goods) || empty($item)) {
            return array();
        }
        $row['price'] = $item['price'];
        $row['price_market'] = $item['price_market'];
        $row['goods_sn'] = $item['goods_sn'];
        $row['store_num'] = $item['store_num'];
        $row['weight'] = $item['weight'];
        $row['spec_array'] = $item['spec_array'];
        $row['goods_id'] = $item['goods_id'];
        $row['item_id'] = $item['item_id'];
        $row['goods_name'] = $goods['goods_name'];
        $row['cuxiao_msg'] = $goods['cuxiao_msg'];
        $row['picture'] = $goods['picture'];
        $row['brand_id'] = $goods['brand_id'];
        $row['status'] = $goods['status'];
        $row['unit'] = $goods['unit'];
		$row['qi_sale'] = $goods['qi_sale'];
        $row['point'] = $goods['point'];
        return $row;
    }
    
    /*
     * APP获得商品购物车行数据
     */
    public function get_item_cart_app($item_id) {
        $MGoodsItem = M('goods_item');
        $item = $MGoodsItem->where(array('item_id'=>$item_id))->find();
        if(empty($item)) {
            return null;
        }
        $goods = $this->field('goods_name,cuxiao_msg,picture,brand_id,status,unit,point')->where(array('goods_id'=>$item['goods_id'],'status'=>1))->find();
        if(empty($goods)) {
            return null;
        }
        $row['price'] = $item['price'];
        $row['price_market'] = $item['price_market'];
        $row['goods_sn'] = $item['goods_sn'];
        $row['store_num'] = $item['store_num'];
        $row['weight'] = $item['weight'];
        $row['spec_array'] = $item['spec_array'];
        $row['goods_id'] = $item['goods_id'];
        $row['item_id'] = $item['item_id'];
        $row['goods_name'] = $goods['goods_name'];
        $row['cuxiao_msg'] = $goods['cuxiao_msg'];
        $row['picture'] = $goods['picture'];
        $row['brand_id'] = $goods['brand_id'];
        $row['status'] = $goods['status'];
        $row['unit'] = $goods['unit'];
        $row['point'] = $goods['point'];
        return $row;
    }
    
    /*
     * 获得单件购物车价格
     */
    public function get_item_price($item_id) {
        $MGoodsItem = M('goods_item');
        return $MGoodsItem->getFieldByItemId($item_id,'price');
    }
    
    /*
     * 获得单件库存
     */
    public function get_item_store_num($item_id) {
        $MGoodsItem = M('goods_item');
        return $MGoodsItem->getFieldByItemId($item_id,'store_num');
    }
    
    /**
     * 获取商品自定义参数
     * @param type $model_id
     * @param type $goods_id
     * @return type
     */
    public function get_goods_attr($model_id, $goods_id) {
        $GoodsModObj = new \Fwadmin\Model\GoodsModModel();
        $attr_list = $GoodsModObj->get_attr_list($model_id, 1);
        foreach($attr_list as $k => $v) {
            $attr_type = $v['attr_type'];
            $attr_name = $v['attr_name'];
            $attr_id = $v['attr_id'];
            $attr_value = $GoodsModObj->get_attr_value($attr_id,$goods_id);//获取已选值
            if(!empty($attr_value)) {
                if($attr_type == 2 || $attr_type == 3) {
                    $attr_value = $GoodsModObj->get_attr_sel_value($attr_value);
                } elseif ($attr_type == 4) {
                    $arr_attr_value = explode(',',trim($attr_value,','));
                    $attr_value = '';
                    foreach($arr_attr_value as $v) {
                        $attr_value .= $GoodsModObj->get_attr_sel_value($v). '&nbsp;&nbsp;';
                    }
                }
            }
            $attr_list[$k]['attr_value'] = $attr_value;
        }
        
        return $attr_list;
    }
    
    /**
     * 增加点击量
     * @param int $goods_id 商品ID
     */
    public function add_hits($goods_id) {
        $this->where(array('goods_id'=>$goods_id))->setInc('count_hits');
    }
    
    /*
     * 更新商品收藏数量
     */
    public function update_count_fav($goods_id) {
        $MemberFavObj = new \Phone\Model\MemberFavModel();
        $count_fav = $MemberFavObj->where(array('goods_id'=>$goods_id))->count();
        return $this->where(array('goods_id'=>$goods_id))->setField('count_fav',$count_fav);
    }
    
    /*
     * 更新商品热销数量
     */
    public function update_count_sale($goods_id) {
        $sql = "select count(1) from ".C('DB_PREFIX')."order_goods g,".C('DB_PREFIX')."order o where g.order_id=o.order_id and g.goods_id='$goods_id' and o.status=3";
        $result = $this->query($sql);
        $count_sale = $result[0][0];
        return $this->where(array('goods_id'=>$goods_id))->setField('count_sale',$count_sale);
    }
    
    /**
     * 获取热销商品
     * @param int $limit 显示个数
     */
    public function get_hot_goods($limit = 8,$cat_ids,$goods_id) {
        $map['status'] = 1;
        //$order = 'count_sale desc';
		$map['is_hot'] = 1;
		$map['cat_path_ids'] = array('like','%,'.$cat_ids.',%');
		$map['goods_id'] = array('neq',$goods_id);
        $list = $this->field('goods_id,goods_name,cuxiao_msg,picture,price')->where($map)->order('order_id asc,goods_id desc')->limit($limit)->select();
		
        foreach($list as $k => $v) {
            $list[$k]['item_id'] = $this->get_default_item_id($v['goods_id']);
        }
        return $list;
    }
    
    /**
     * 获取热销商品
     * @param int $limit 显示个数
     */
    public function get_new_goods($limit = 8) {
        $map['status'] = 1;
        $order = 'time_create desc';
        $list = $this->field('goods_id,goods_name,picture,price,count_sale')->where($map)->order($order)->limit($limit)->select();
        foreach($list as $k => $v) {
            $list[$k]['item_id'] = $this->get_default_item_id($v['goods_id']);
        }
        return $list;
    }
    
    /*
     * 浏览历史记录添加
     */
    public function history_add($goods_id) {
        $goods_history = cookie('goods_history');
        if(!empty($goods_history)) {
            $arr_goods_history = unserialize(stripslashes($goods_history));  
        }
        $arr_goods_history[] = $goods_id;
        cookie('goods_history',  serialize($arr_goods_history));
    }
    
    /**
     * 获取浏览历史记录
     * @param int $limit 显示个数
     */
    public function history_show($limit = 8) { 
        $goods_history = cookie('goods_history');
        if(!empty($goods_history)) {
            $arr_goods_history = unserialize(stripslashes($goods_history));
            array_reverse($arr_goods_history);//反序
            $str_goods_history = implode(',', $arr_goods_history);
            $map['goods_id'] = array('in',$str_goods_history);
            $map['status'] = 1;
            $list = $this->field('goods_id,goods_name,picture,price_market,price,count_sale')->where($map)->limit($limit)->select();
            foreach($list as $k => $v) {
                $list[$k]['picture'] = str_replace('products', 'products/thumb', $list[$k]['picture']);
            }
            return $list;
        } else {
            return array();
        }
    }
	
	
	  /*
     * 搜索历史记录添加
     */
    public function search_history_add($keyword) {
        $search_history = cookie('search_history');
        if(!empty($search_history)) {
            $arr_search_history = unserialize(stripslashes($search_history));  
        }
        $arr_search_history[] = $keyword;
        cookie('search_history',  serialize($arr_search_history));
    }
    
     /**
     * 获取搜索历史记录
     * @param int $limit 显示个数
     */
	 
	     public function search_history_show($limit = 8) { 
        $search_history = cookie('search_history');
        if(!empty($search_history)) {
           $arr_search_history = unserialize(stripslashes($search_history));
           $list = array_reverse($arr_search_history);//反序
          
           $list = array_unique($list);
		  return array_slice($list,0,$limit,true);
        } else {
            return array();
        }
    }

}
